<?php

declare(strict_types=1);

namespace app\common\model;

use addons\Target\facade\Target;
use think\facade\Cache;
use think\facade\Event;

class User extends Base
{

    protected $name = 'user';

    protected $type = [
        'active_time' => 'timestamp',
    ];

    protected function level()
    {
        return $this->hasOne(Level::class, 'id', 'level_id');
    }

    public function assets()
    {
        return $this->hasOne(Assets::class, 'uid');
    }

    public function getNicknameAttr($value)
    {
        return $value ?: Cache::get('system')['default_nickname'];
    }

    public function getPhotoAttr($value)
    {
        return $value ?: Cache::get('system')['default_photo'];
    }

    protected function getMinTeamAttr($value, $data)
    {
        return self::geMinTeam($data['id']);
    }

    public function getEquityTextAttr($value, $data)
    {
        return self::getEquityStatus($data['equity']);
    }

    public static function getEquityStatus($value, $type = 1)
    {
        $status = [0 => '无', 1 => '绿色权益', 2 => '红色权益', 3 => '黄色权益'];
        return $type == 1 ? $status[$value] : $status;
    }

    public static function _save($param, $logs)
    {
        $sys = \app\common\controller\Config::lists();
        parent::startTrans();
        try {
            if (isset($param['id']) && $param['id']) {
                $original = self::where($logs['pk'], $param[$logs['pk']])->find();
                if (empty($original)) {
                    return ['code' => -1, 'msg' => '记录不存在，请检查！'];
                }

                $logs['original'] = $original;
                $model = self::update($param);
                $ids = self::getTeam($param['id']);
                parent::whereIn('id', $ids)->update(['tag' => $param['tag']]);
                $logs['operation'] = 'save';
                if ($logs['writeLog']) {
                    $logs['model'] = $model;
                    Event::trigger('Logs', $logs);
                }
            } else {
                $count = parent::where(['code' => $param['code']])->count();
                if ($count) {
                    return ['code' => -1, 'msg' => '会员编号已被注册'];
                }
                $count = parent::where(['mobile' => $param['mobile']])->count();
                if ($count) {
                    return ['code' => -1, 'msg' => '手机号已被注册'];
                }
                if (!isset($param['parent_code']) || empty($param['parent_code'])) {
                    $param['parent_code'] = 'admin';
                }
                $parent = parent::where(['code' => $param['parent_code']])->find();
                if (empty($parent)) {
                    return ['code' => -1, 'msg' => '推荐人不存在'];
                }

                if ($sys['is_sms'] == 1) {
                    if (isset($param['captcha'])) {
                        if (empty($param['captcha'])) {
                            return ['code' => -1, 'msg' => '验证码不能为空！'];
                        }
                        $smscode = Code::where(['mobile' => $param['mobile'], 'code' => $param['captcha'], 'status' => 0, 'type' => 'register'])->where('end_time', '>', time())->find();
                        if (empty($smscode)) {
                            return ['code' => -1, 'msg' => '短信已过期'];
                        }
                        $smscode->status = 1;
                        $smscode->save();
                    }
                }
                $param['tag'] = $parent->tag;
                $param['parent_id'] = $parent->id;
                $param['parent_name'] = $parent->nickname;

                $param['code'] = trim($param['code']);
                $param['mobile'] = trim($param['mobile']);
                $param['password'] = !empty($param['password']) ? md5($param['password']) : md5('111111');
                $param['pay_password'] = !empty($param['pay_password']) ? md5($param['pay_password']) : md5('222222');
                parent::create($param);
            }
            parent::commit();
            return ['code' => 1, 'msg' => '操作成功', 'url' => url('login/index')->build()];
        } catch (\Exception $e) {
            parent::rollback();
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    public static function onAfterInsert($model)
    {
        if ($model->parent_code) {
            Relation::generate($model->id, $model->code, $model->parent_id, $model->parent_code);
        }
        $model->assets()->save(['uid' => $model->id]);

        Event::trigger('Statistics', ['key' => 'user', 'value' => 1]);
    }


    public static function recharge($param, $admin)
    {
        parent::startTrans();
        try {
            $user = parent::find($param['id']);
            if ($user->isEmpty()) {
                return json(['code' => -1, 'msg' => '未查询到相关会员']);
            }
            $account = get_pay_way($param['account']);
            if ($param['mode'] == 1) {
                Target::Account()
                    ->basics($param['id'], $param['account'], $param['amount'], '后台充值', '+')
                    ->setMsg($param['remarks'])
                    ->setOperator($admin->admin_name)
                    ->createRecharge();
                $logs = '后台充值【' . $account . '】金额【' . $param['amount'] . '】会员【' . $user->code . '】';
            } else {
                Target::Account()
                    ->basics($param['id'], $param['account'], $param['amount'], '后台扣除', '-')
                    ->setMsg($param['remarks'])
                    ->setOperator($admin->admin_name)
                    ->createRecharge();
                $logs = '后台扣除【' . $account . '】金额【' . $param['amount'] . '】会员【' . $user->code . '】';
            }
            self::isValid();
            Logs::adds($logs, $admin['id'], $admin['admin_name']);

            parent::commit();
            return json(['code' => 1, 'msg' => '操作成功']);
        } catch (\Exception $e) {
            parent::rollback();
            return json(['code' => -1, 'msg' => $e->getMessage()]);
        }
    }


    /**
     * 检测用户收款方式
     * @param $user
     */
    public static function checkReceipt($user)
    {
        // 微信
        if (
            empty($user->wechat_name) && empty($user->wechat_image)
            && empty($user->alipay_name) && empty($user->alipay_image)
            && empty($user->bank_name) && empty($user->bank_number)
        ) {
            return false;
        }
        return true;
    }

    /**
     * @param $uid
     * @return float|int
     * 原点 2021年12月28日11:50:17 计算小区业绩
     */
    public static function geMinTeam($uid)
    {
        $areaData = parent::where('parent_id', $uid)->order('team_total', 'desc')->column('my_total+team_total as team_total');
        if ($areaData) {
            array_shift($areaData);
            if (!empty($areaData)) return array_sum($areaData);
        }
        return 0;
    }


    public static function security($param, $user, $first = false): array
    {
        try {
            $pass = $param['type'];
            $msg = '已设置';
            if (!$first) {
                if (md5($param['old_password']) != $user->$pass) {
                    return ['code' => -1, 'msg' => '旧密码错误'];
                }
                if (md5($param['old_password']) == md5($param['password'])) {
                    return ['code' => -1, 'msg' => '新旧密码相同'];
                }
                $msg = '已修改';
            }

            $user->$pass = md5($param['password']);
            if ($pass == 'password') {
                $user->token = md5(time() . json_encode($user));
                cookie('token', null);
            }
            $user->save();

            return ['code' => 1, 'msg' => $msg];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
    /**
     * 是否是有效会员
     */
    public static function isValid()
    {
        $sys = \app\common\controller\Config::lists();
        try {
            $y_uid = Assets::where('help_money', '>=', $sys['help_valid'])->column('uid'); //获得有效账户
            $n_uid = Assets::where('help_money', '<', $sys['help_lose'])->column('uid'); //失去有效账户
            parent::whereIn('id', $n_uid)->where(['is_valid' => 1])->update(['is_valid' => 0, 'valid_time' => time() + 86400 * $sys['help_day']]);
            parent::whereIn('id', $y_uid)->where(['is_valid' => 0])->update(['is_valid' => 1, 'valid_time' => 0]);
            return ['code' => 1, 'msg' => '成功！'];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
    /**
     * 获取所有团队人数
     */
    public static function getTeam($uid)
    {
        $team = Relation::where(['uid' => $uid])->order('algebra asc')->column('new_uid');
        return $team;
    }
}
